package org.jeecg.common.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 接口请求	
 *--------------------------------------------------->
 * @Author WangWei                                                                      
 * @date 2018年8月17日 上午9:36:27           
 * @version V1.0                       
 * @Email 1246518873@qq.com               
 *--------------------------------------------------->
 * @Description:  
 *
 *
 */
public class HttpRequest {
	
	static Log log = LogFactory.getLog(HttpRequest.class);

	
	public static String sendGet(String url){
		StringBuffer buffer = new StringBuffer();
		try {
			URL serverUrl = new URL(url);  
			HttpURLConnection conn = (HttpURLConnection) serverUrl.openConnection();  
			conn.setRequestMethod("GET");  
			//必须设置false，否则会自动redirect到重定向后的地址  
			conn.setInstanceFollowRedirects(false);
			conn.addRequestProperty("Accept-Charset", "UTF-8;");  
			conn.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.8) Firefox/3.6.8");  
			conn.addRequestProperty("Referer", "http://matols.com/");  
			conn.connect();  
			
			//判定是否会进行302重定向
			if (conn.getResponseCode() == 302) { 
				//如果会重定向，保存302重定向地址，以及Cookies,然后重新发送请求(模拟请求)
				String location = conn.getHeaderField("Location");  
				String cookies = conn.getHeaderField("Set-Cookie");  
				
				serverUrl = new URL(location);  
				conn = (HttpURLConnection) serverUrl.openConnection();  
				conn.setRequestMethod("GET");
				conn.setRequestProperty("Cookie", cookies);
				conn.addRequestProperty("Accept-Charset", "UTF-8;");  
				conn.addRequestProperty("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.8) Firefox/3.6.8");  
				conn.addRequestProperty("Referer", "http://matols.com/");  
				conn.connect();  
			}
			
			//将返回的输入流转换成字符串  
			InputStream inputStream = conn.getInputStream();  
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"utf-8");  
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader); 
			String str = null;  
			while ((str = bufferedReader.readLine()) != null) {  
				buffer.append(str);  
			}  
			bufferedReader.close();  
			inputStreamReader.close();  
			// 释放资源  
			inputStream.close();  
			inputStream = null;  
		} catch (Exception e) {
			e.printStackTrace();
		}
		return buffer.toString();
	}
	

    /**
     * post请求
     * @param url
     * @param json
     * @return
     */
    public static String doPost(String url,JSONObject json){
    	//SSLUtils.setSSL();
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();
        post.setConfig(requestConfig);
        String response = null;
        try {
            StringEntity s = new StringEntity(json.toString());
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");//发送json数据需要设置contentType
            post.setEntity(s);
            HttpResponse res = httpclient.execute(post);
            if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
            	response = EntityUtils.toString(res.getEntity());// 返回json格式：
            	System.err.println(response);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return response;
    }
	
    public static String post(String strURL, String params) {
        BufferedReader reader = null;
        System.out.println(params);
        try {
            URL url = new URL(strURL);// 创建连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST"); // 设置请求方式
            connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
            connection.connect();
            //一定要用BufferedReader 来接收响应， 使用字节来接收响应的方法是接收不到内容的
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
            out.append(params);
            	
            
            out.flush();
            out.close();
            // 读取响应
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            String res = "";
            while ((line = reader.readLine()) != null) {
                res += line;
            }
            reader.close();
            
 
            return res;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "error"; // 自定义错误信息
    }
}
